import { _decorator, Component, instantiate, log, math, Node, Prefab, UITransform, view } from 'cc';
import { Enemy } from './Enemy';
import { GameScene } from './GameScene';
import { L } from './tools/L';
const { ccclass, property } = _decorator;

@ccclass('EnemyManager')
export class EnemyManager extends Component {
    @property
    enemy0SpawnRate: number = 1;
    @property(Prefab)
    enemy0Prefab: Prefab;

    @property
    enemy1SpawnRate: number = 2;
    @property(Prefab)
    enemy1Prefab: Prefab;

    @property
    enemy2SpawnRate: number = 5;
    @property(Prefab)
    enemy2Prefab: Prefab;

    @property([Node])
    enemyArray: Node[] = [];

    start() {
        this.schedule(() => this.doSpawn(this.enemy0Prefab), this.enemy0SpawnRate);
        this.schedule(() => this.doSpawn(this.enemy1Prefab), this.enemy1SpawnRate);
        this.schedule(() => this.doSpawn(this.enemy2Prefab), this.enemy2SpawnRate);
    }

    protected onDestroy(): void {
        this.unscheduleAllCallbacks();
    }

    update(dt: number) {

    }

    doSpawn(prefab: Prefab) {
        const enemy = instantiate(prefab);
        this.node.addChild(enemy);

        // 获取尺寸信息
        const contentSize = enemy.getComponent(UITransform).contentSize;
        const screenSize = view.getVisibleSize();

        // 计算安全的X轴生成范围（确保不会超出屏幕左右边界）
        const minX = -screenSize.width / 2 + contentSize.width / 2;
        const maxX = screenSize.width / 2 - contentSize.width / 2;

        // 确保计算出的边界有效（如果节点比屏幕还大）
        const safeMinX = Math.min(minX, 0);
        const safeMaxX = Math.max(maxX, 0);

        // 随机X位置
        const randomX = math.randomRangeInt(safeMinX, safeMaxX);

        // Y位置：刚好在屏幕上方（完全不可见）
        const spawnY = screenSize.height / 2 + contentSize.height / 2;

        // 设置位置
        enemy.setPosition(
            randomX,
            spawnY,
            this.node.getPosition().z
        );

        L.debug(`Enemy[${enemy.name}] 新产生, 坐标:[ ${enemy.getPosition()} ]`);
        GameScene.inst.addEnemy(enemy);
    }
}

